package com.sgg.gulimall_product.exception;


import cn.hutool.core.util.ObjectUtil;
import com.sgg.gulimall_common.api.Result;
import com.sgg.gulimall_common.api.ResultCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result ValidatorExecptionHandler(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        String message = null;
        if(result.hasErrors()){
            FieldError error = result.getFieldError();
            if(ObjectUtil.isNotNull(error)){
                message = error.getField()+error.getDefaultMessage();
            }
        }
        return Result.failed(ResultCode.VALIDATE_FAILED,message);
    }


}
